package com.chevip.article.sync;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class HttpRequester {

    private static final int DEFAULT_CONNECTTIMEOUT = 5000;
    private static final int DEFAULT_READTIMEOUT = 30000;

    public static String sendGet(String url) {
        HttpURLConnection httpConn = getHttpComm(url);
        return sendGet(httpConn);
    }

    public static String sendGet(String url, int connectTimeout, int readTimeout) {
        HttpURLConnection httpConn = getHttpComm(url, connectTimeout, readTimeout);
        return sendGet(httpConn);
    }

    public static String sendGet(String url, Map<String, String> parameters, int connectTimeout, int readTimeout) {
        String full_url = url + "?" + initParams(parameters);
        return sendGet(full_url, connectTimeout, readTimeout);
    }

    public static String sendGet(HttpURLConnection httpConn) {
        if (httpConn == null) {
            return "";
        }
        String result = "";
        BufferedReader in = null;
        try {
            httpConn.connect();
            // 响应头部获取
/*			Map<String, List<String>> headers = httpConn.getHeaderFields();
			for (String key : headers.keySet()) {
				System.out.println(key + "\t：\t" + headers.get(key));
			}*/
            // 定义BufferedReader输入流来读取URL的响应,并设置编码方式
            in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "GBK"));
            String line;// 读取返回的内容
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static String sendPost(String url, Map<String, String> parameters) {
        return sendPost(getHttpComm(url), parameters);
    }

    public static String sendPost(String url, Map<String, String> parameters, int connectTimeout, int readTimeout) {
        return sendPost(getHttpComm(url, connectTimeout, readTimeout), parameters);
    }

    public static String sendPost(HttpURLConnection httpConn, Map<String, String> parameters) {
        String result = "";// 返回的结果
        BufferedReader in = null;// 读取响应输入流
        PrintWriter out = null;
        String params = "";// 编码之后的参数
        try {
            // 编码请求参数
            params = initParams(parameters);
            httpConn.setRequestMethod("POST");
            // 设置POST方式
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);

            out = new PrintWriter(httpConn.getOutputStream()); // 获取HttpURLConnection对象对应的输出流
            out.write(params); // 发送请求参数
            out.flush();// flush输出流的缓冲
            in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "GBK"));// 定义BufferedReader输入流来读取URL的响应，设置编码方式
            String line;
            while ((line = in.readLine()) != null) { // 读取返回的内容
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static HttpURLConnection getHttpComm(String url) {
        HttpURLConnection httpConn = getHttpComm(url, DEFAULT_CONNECTTIMEOUT, DEFAULT_READTIMEOUT);
        return httpConn;
    }

    public static HttpURLConnection getHttpComm(String url, int connectTimeout, int readTimeout) {
        HttpURLConnection httpConn = null;
        try {
            URL connURL = new URL(url);
            httpConn = (HttpURLConnection) connURL.openConnection();
            httpConn.setConnectTimeout(connectTimeout);
            httpConn.setReadTimeout(readTimeout);
            httpConn.setRequestMethod("GET");

            // 设置通用属性
            httpConn.setRequestProperty("Accept", "*/*");
            httpConn.setRequestProperty("Connection", "Keep-Alive");
            httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return httpConn;
    }

    public static String urlEncoder(String url) {
        try {
            return java.net.URLEncoder.encode(url, "GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return url;
    }

    // 构造请求参数
    private static String initParams(Map<String, String> parameters) {
        StringBuffer sb = new StringBuffer();
        if (parameters.size() == 1) {
            for (String name : parameters.keySet()) {
                sb.append(name).append("=").append(urlEncoder(parameters.get(name)));
            }
            return sb.toString();
        } else {
            for (String name : parameters.keySet()) {
                sb.append(name).append("=").append(urlEncoder(parameters.get(name))).append("&");
            }
            String temp_params = sb.toString();
            return temp_params.substring(0, temp_params.length() - 1);
        }
    }
}
